package com.tjec.project.common;

import com.tjec.common.constant.Constants;
import com.tjec.common.exception.user.UserException;
import com.tjec.common.utils.IdUtils;
import com.tjec.common.utils.MessageUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.common.utils.VerifyCodeUtils;
import com.tjec.common.utils.sign.Base64;
import com.tjec.framework.manager.AsyncManager;
import com.tjec.framework.manager.factory.AsyncFactory;
import com.tjec.framework.redis.RedisCache;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.project.msg.service.MsgService;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.service.ISysUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author tjec
 */
@RestController
public class CaptchaController {
    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private MsgService msgService;
    
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(stream.toByteArray()));
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        } finally {
            stream.close();
        }
    }

    /**
     * 生成短信验证码
     * @param phonenumber 手机号
     * @return
     * @throws IOException
     */
    @GetMapping("/loginCaptchaSMS")
    public AjaxResult LoginCaptchaSMS(HttpServletResponse response, String phonenumber) throws IOException {
        if (StringUtils.isBlank(phonenumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        //根据手机号获取用户名
	    SysUser sysUser = iSysUserService.selectUserByPhonenumber(phonenumber);
	    if (null == sysUser) {
	        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.mobile.not.exists")));
	        throw new UserException("user.mobile.not.exists", null);
	    }
        
        Random random = new Random();
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.getCaptchaSMS();
        
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + phonenumber + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, Constants.SMS_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //发送短信（未实现）
        msgService.SendMsg2(phonenumber,"您的验证码是："+ verifyCode+"，5分钟内有效，请勿泄漏。如非本人操作，请忽略此信息。");
        
        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        //上线后，删除返回值
        ajax.put("verifyCode", verifyCode);
        return ajax;
    }

    /**
     * 生成短信验证码
     * @param phonenumber 手机号
     * @return
     * @throws IOException
     */
    @GetMapping("/captchaSMS")
    public AjaxResult getSMSCode(HttpServletResponse response, String phonenumber) throws IOException {
        if (StringUtils.isBlank(phonenumber)) {
            return AjaxResult.error("手机号不能为空");
        }
        Random random = new Random();
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.getCaptchaSMS();

        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + phonenumber + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, Constants.SMS_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //发送短信（未实现）
        msgService.SendMsg2(phonenumber,"您的验证码是："+ verifyCode+"，5分钟内有效，请勿泄漏。如非本人操作，请忽略此信息。");

        AjaxResult ajax = AjaxResult.success();
        ajax.put("uuid", uuid);
        //上线后，删除返回值
        ajax.put("verifyCode", verifyCode);
        return ajax;
    }
}
